from django.http import HttpResponse, JsonResponse

# Create your views here.
from django.shortcuts import redirect, render

from staff.models import staff


# 不用ajax做后台的登陆校验，已弃用
def login_check(request):
    # 获取提交的用户名和密码
    username = request.POST.get('username')
    password = request.POST.get('password')
    # print(username + password)
    # 进行登陆校验
    user = staff.objects.get(name__exact=username)
    if password == user.password:
        # 返回应答
        return HttpResponse('ok')
    else:
        return HttpResponse('sorry')


# ajax做后台登陆校验，并设置cookie保留用户信息
def login_check_ajax(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    remember = request.POST.get('remember')
    userlist = staff.objects.filter(name__exact=username)
    if len(userlist) == 0:
        return JsonResponse({'res': 0})
    user = userlist[0]

    if password == user.password:
        response = redirect('/index')
        # 是否保留用户信息
        if remember == 'on':
            response.set_cookie('username', username, max_age=7 * 24 * 3600)
            response.set_cookie('password', password, max_age=7 * 24 * 3600)
        # 写下登陆状态
        request.session['islogin'] = True
        request.session.set_expiry(0)
        # 返回应答
        return response
    else:
        return JsonResponse({'res': 0})


def query(request):
    all_staffs = staff.objects.all()
    return render(request, 'staff/staffInfo.html', {'staff_list': all_staffs})
